"""从 CSV 导入用户与文章数据。

CSV 列示例：
 users.csv: username,email,password,is_admin
 articles.csv: title,content,visibility,author_email

用法：
  python -m tests.scripts.import_csv --users users.csv --articles articles.csv
"""

import os
import csv
import argparse

from app import create_app, db
from app.models import User, Article, ArticleVisibility


def import_users(path: str):
	with open(path, newline='', encoding='utf-8') as f:
		for row in csv.DictReader(f):
			username = row.get('username')
			email = row.get('email')
			password = row.get('password', 'Pass@123')
			is_admin = str(row.get('is_admin', '')).strip().lower() in {"1", "true", "yes"}
			if not username or not email:
				continue
			if User.query.filter((User.username == username) | (User.email == email)).first():
				continue
			u = User(username=username, email=email, is_admin=is_admin)
			u.set_password(password)
			db.session.add(u)


def import_articles(path: str):
	with open(path, newline='', encoding='utf-8') as f:
		for row in csv.DictReader(f):
			title = row.get('title')
			content = row.get('content')
			visibility = row.get('visibility', 'public')
			author_email = row.get('author_email')
			if not title or not content or not author_email:
				continue
			author = User.query.filter_by(email=author_email).first()
			if not author:
				continue
			vis = ArticleVisibility.public
			try:
				vis = ArticleVisibility(visibility)
			except Exception:
				pass
			art = Article(title=title, content=content, visibility=vis, author_id=author.id)
			db.session.add(art)


def main():
	parser = argparse.ArgumentParser()
	parser.add_argument("--users", dest="users_csv", default=None)
	parser.add_argument("--articles", dest="articles_csv", default=None)
	args = parser.parse_args()

	os.environ.setdefault("DB_TYPE", "sqlite")
	os.environ.setdefault("SQLITE_PATH", os.path.join(os.getcwd(), "rbac.sqlite3"))
	app = create_app(os.getenv("FLASK_ENV", "development"))
	with app.app_context():
		if args.users_csv:
			import_users(args.users_csv)
		if args.articles_csv:
			import_articles(args.articles_csv)
		db.session.commit()
		print("CSV 导入完成")


if __name__ == "__main__":
	main()


